<template>
  <div class="file-list-container">
    <!-- 搜索表单 -->
    <el-form :inline="true">
      <div class="right">
        <el-form-item>
          <el-upload
            v-model:file-list="uploadFileList"
            class="upload-demo"
            :headers="{ Authorization: token }"
            :action="`${baseurl}/file/uploadFile`"
            :on-success="handleSuccess"
            :multiple="true"
            :on-exceed="handlExceed"
            :show-file-list="false"
            :limit="3"
          >
            <el-button type="primary" size="default" v-if="userStore.UserInfo.identity !== '用户'"
              >上传文件</el-button
            >
          </el-upload>
        </el-form-item>
      </div>
    </el-form>
    <!-- 主体表格 -->
    <div class="table">
      <el-table :data="fileList">
        <el-table-column type="index" width="55"></el-table-column>
        <el-table-column label="文件名" align="center" type="default" prop="file_name">
          <template v-slot="{ row }">
            <a :href="row.file_url" :download="row.file_name" @click="updateDownloadNumber(row)">{{
              row.file_name
            }}</a>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" align="center" type="default" prop="file_size">
          <template v-slot="{ row }"> {{ row.file_size?.toFixed(1) }}KB </template>
        </el-table-column>
        <el-table-column
          label="上传者"
          align="center"
          type="default"
          prop="upload_person"
          min-width="90"
        />
        <el-table-column
          label="下载、预览次数"
          align="center"
          type="default"
          prop="download_number"
        />

        <el-table-column label="上传时间" align="center" type="default" min-width="170"
          ><template v-slot="{ row }">
            {{ formaDate(row.upload_time) }}
          </template></el-table-column
        >
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <el-popconfirm
              :title="`你确定要删除此文件吗`"
              confirm-button-text="确认"
              cancel-button-text="取消"
              @confirm="toRecycli(row)"
              width="250px"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  :disabled="userStore.UserInfo.identity !== '超级管理员'"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template></el-table-column
        >
      </el-table>
      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          class="pagination"
          v-model:current-page="page"
          :page-size="10"
          layout="prev, pager, next, jumper,total"
          :total="total"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import moment from 'moment'
import { onMounted, ref, watch } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { ElMessage, type UploadProps, type UploadUserFile } from 'element-plus'
import {
  bingFileAndUserAPI,
  deleteFileAPI,
  getFileListAPI,
  updateDownloadNumberAPI
} from '@/api/file'
import { useUserStore } from '@/stores/user'
import { tracking } from '@/utils/operation'

const userStore = useUserStore()
const baseurl = import.meta.env.VITE_APP_BASE_API

const activeName = defineProps(['activeName'])
/** 处理日期 */
const formaDate = (date: string) => {
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

// 分页器数据
const page = ref<number>(1)
const total = ref<number>()

const token = localStorage.getItem('TOKEN')

/** 合同列表 */
const fileList = ref<FileList[]>([])
const getFileList = async () => {
  const res = await getFileListAPI(page.value)
  total.value = res.total
  fileList.value = res.data!
}

/** 删除 */
const toRecycli = async (row: FileList) => {
  await deleteFileAPI(row.id, row.file_name)
  ElMessage({ type: 'success', message: '删除成功' })
  /** 记录操作 */
  tracking('文件', userStore.UserInfo?.name!, row.file_name, '高级', `删除`)
  getFileList()
}
/*************** */

const uploadFileList = ref<UploadUserFile[]>([])

const handlExceed: UploadProps['onExceed'] = () => {
  ElMessage({ type: 'warning', message: '最多上传三个文件' })
}
/** 文件上传成功回调 */
const handleSuccess = async (res: any) => {
  if (res.status === 1) {
    await bingFileAndUserAPI(userStore.UserInfo.name!, res.url)
    ElMessage({ type: 'success', message: '上传成功' })
    tracking('文件', userStore.UserInfo?.name!, res.data, '中级', `上传`)
    getFileList()
  } else {
    ElMessage({ type: 'error', message: '上传失败，请稍后再试' })
  }
}

const updateDownloadNumber = async (row: FileList) => {
  await updateDownloadNumberAPI(row.download_number, row.id)
  getFileList()
}

/****************** */

watch([page, activeName], () => {
  getFileList()
})
onMounted(() => {
  getFileList()
})
</script>

<style scoped lang="scss">
.file-list-container {
  padding: 8px;
  .el-form {
    display: flex;
    justify-content: right;
    .el-form-item {
      margin: 0;
    }
  }
  .el-table {
    margin-top: 10px;
  }
  .pagination {
    display: flex;
    justify-content: center;
    margin: 15px;
  }
}
</style>
